package com.chenchao.collection.stream;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/5 12:48
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.collection.stream.Test09.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 流的收集
 */
public class Test09 {
    public static void main(String[] args) {
        //testList();
        //testSet();
        testMap();
    }

    /**
     * 收集到list中
     */
    public static void testList(){
        Integer[] integers = {1, 3, 2, 7, 8, 3, 8};
        Stream<String> stream = Stream.of(integers).
                filter(integer -> integer >= 3).
                map(integer -> "元素" + integer);
        List<String> collect = stream.collect(Collectors.toList());
        /*收集完之后也会被关闭*/
        stream.forEach(System.out::println);

        collect.forEach(System.out::println);
    }
    /**
     * 收集到set中
     */
    public static void testSet(){
        Integer[] integers = {1, 3, 2, 7, 8, 3, 8};
        Set<Integer> collect = Stream.of(integers).
                filter(integer -> integer >= 3).collect(Collectors.toSet());
        /*收集到集合中，集合会自动去重*/
        collect.forEach(System.out::println);
    }
    /**
     * 收集到map中
     */
    public static void testMap(){
        /*把数值大于3的以名字作为key,数值作为value填入到map*/
        String[] strings = {"喜羊羊,2", "美羊羊,3", "沸羊羊,5","懒羊羊,4"};
        Stream<String> stream = Stream.of(strings).
                filter(s -> (Integer.parseInt(s.split(",")[1]) > 3));
        Map<String, Integer> collect = stream.collect(Collectors.toMap(s -> s.split(",")[0],
                s -> Integer.parseInt(s.split(",")[1])));
        collect.forEach((s,i)-> System.out.println("key:"+s+",value:"+i));
    }
}
